<?php

namespace app\interfaces\model;

use think\Model;
use think\Request;

class MemberDistribution extends Model
{

    // 模型事件
    protected static function init()
    {
        // 写入前
        self::event('before_write', function ($data) {
            // $data->distribution_id = Request::instance()->param('distribution_id');
            // $data->referrals_id = Request::instance()->param('referrals_id');
            $data->hierarchy = self::dispose_hierarchy($data->distribution_id);
            $data->level = self::dispose_level($data->distribution_id);
            $data->create_time = time();
        });
    }

    // hierarchy方法
    protected static function dispose_hierarchy($distribution_id)
    {

        $find = self::where(['referrals_id' => $distribution_id])->value('hierarchy');

        if (!empty($find))
            return $find . Request::instance()->param('distribution_id') . ',';
        else
            return '0,' . Request::instance()->param('distribution_id') . ',';
    }

    // level方法
    protected static function dispose_level($distribution_id)
    {

        $find = self::where(['referrals_id' => $distribution_id])->value('level');

        if (!empty($find))
            return (int)$find + 1;
        else
            return 1;
    }

    //分销列表下线人和分销订单一对多
    public function memberDistributionOrder()
    {
        return $this->hasMany('MemberDistributionOrder','member_id','referrals_id');
    }
    //分销列表和会员表一对一  (分销人)
    public function member()
    {
        return $this->belongsTo('Member','referrals_id','id')->field('id,nickname,avatar,username,suffer');
    }

}
